package com.gotkicry.asynctask_listview;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    ListView listView;
    List<JsonBean> list;
    MyAdapter adapter;
    private static String url = "https://www.imooc.com/api/teacher?type=4&num=30";
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if(msg.what == 0){
                adapter = new MyAdapter(list);
                listView.setAdapter(adapter);
                adapter.notifyDataSetChanged();
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        new Thread(new Runnable() {
            @Override
            public void run() {
                list = getJsonData();
                Log.d(TAG, "run: "+list.size());
            }
        }).start();
    }

    private void initView() {
        listView = findViewById(R.id.listview);
        list = new ArrayList<>();
    }


    private List<JsonBean> getJsonData(){
        List<JsonBean> list = new ArrayList<>();
        String jsonString = null;
        try {
            jsonString = readStream(new URL(url).openStream());
            JSONObject jsonObject = new JSONObject(jsonString);
            JSONArray jsonArray = jsonObject.getJSONArray("data");
            for(int i = 0; i < jsonArray.length();i++){
                JSONObject jsob = jsonArray.getJSONObject(i);
                JsonBean jsonBean = new JsonBean();
                jsonBean.setPicSmall(jsob.getString("picSmall"));
                jsonBean.setName(jsob.getString("name"));
                jsonBean.setDescription(jsob.getString("description"));
                list.add(jsonBean);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Log.d(TAG, "getJsonData: "+jsonString);
        Log.d(TAG, "getJsonData: "+list.size());
        handler.sendEmptyMessage(0);
        return list;
    }

    private String readStream(InputStream in){
        InputStreamReader inputStreamReader;
        String result = "";


        try {
            String line = "";
            inputStreamReader = new InputStreamReader(in,"UTF-8");
            BufferedReader reader = new BufferedReader(inputStreamReader);
            while ((line = reader.readLine()) != null){
                result += line;
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Log.d(TAG, "readStream: "+result);
        return result;
    }

    class MyAdapter extends BaseAdapter {
        List<JsonBean> list;

        public MyAdapter(List<JsonBean> list) {
            this.list = list;
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder = null;
            if(viewHolder == null){
                convertView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.item_list, parent, false);
                viewHolder = new ViewHolder(convertView);
                convertView.setTag(viewHolder);
            }else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            JsonBean jsonBean = list.get(position);
            //默认图标
            viewHolder.mImgIcon.setImageResource(R.drawable.ic_launcher_foreground);
            String url = jsonBean.getPicSmall();
            //setTag防止错位
            viewHolder.mImgIcon.setTag(url);
            new ImageLoader().showImageByAsynTask(viewHolder.mImgIcon,jsonBean.getPicSmall());
            viewHolder.mTextTitle.setText(jsonBean.getName());
            viewHolder.mTextContext.setText(jsonBean.getDescription());
            Log.d(TAG, "getView: "+list.size());
            return convertView;
        }

        class ViewHolder {
            View view;
            ImageView mImgIcon;
            TextView mTextContext,mTextTitle;

            ViewHolder(View view) {
                this.view = view;
                this.mTextTitle = view.findViewById(R.id.text_title);
                this.mImgIcon = (ImageView) view.findViewById(R.id.img_icon);
                this.mTextContext = (TextView) view.findViewById(R.id.text_context);
            }
        }
    }

}
